<%@ page import="com.cy.model.Menu" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<c:set var="menuTypes" value="<%= Menu.Type.toJson()%>"/>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link href="../styles/dpl-min.css" rel="stylesheet"/>
    <link href="../styles/bui-min.css" rel="stylesheet"/>
    <link href="../styles/main.css" rel="stylesheet"/>
</head>
<body>

<!--列表页-->
<div class="container">
    <!-- 工具栏 -->
    <div id="toolbar"></div>
    <div id="tab"></div>
    <div style="padding-top: 10px;">
        <div class="search-grid-container">
            <!-- 树形表格 -->
            <div id="menuGrid"></div>
        </div>
    </div>
</div>

<div id="ModelFormDialog" style="display: none">
    <form id="ModelForm" class="form-horizontal">
        <div class="control-group">
            <label class="control-label">名称：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="menu.name" data-rules="{required:true}"/>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">Url：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="menu.url" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">请求方式：</label>
            <div class="controls">
                <select name="menu.method">
                    <option value="">无</option>
                    <option value="GET">GET</option>
                    <option value="POST">POST</option>
                    <option value="HEAD">HEAD</option>
                    <option value="OPTIONS">OPTIONS</option>
                    <option value="PUT">PUT</option>
                    <option value="DELETE">DELETE</option>
                    <option value="TRACE">TRACE</option>
                </select>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">类型：</label>
            <div class="controls">
                <select name="menu.type">
                </select>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">父菜单：</label>
            <div class="controls">
                <select name="menu.parent_id" id="parent_item">
                    <option value="">无</option>
                </select>
            </div>
        </div>
        <div class="row form-actions actions-bar">
            <div class="span13 offset3 ">
                <button type="submit" class="button button-primary">保存</button>
                <button type="reset" class="button">重置</button>
            </div>
        </div>
    </form>
</div>

<script type="text/javascript" src="../scripts/jquery/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../scripts/bui.js"></script>
<script type="text/javascript" src="../scripts/treegrid-min.js"></script>
<script type="text/javascript" src="../scripts/common/search.js"></script>
<script type="text/javascript">
    var MENU_TYPES = ${menuTypes};
    BUI.use(['bui/extensions/treegrid', 'bui/overlay', 'bui/toolbar', 'bui/form', 'bui/data', 'bui/tab'],function (TreeGrid, Overlay, Toolbar, Form, Data, Tab){
        var url = "../clmp/menu";
        var module = 'menu';
        //数据仓库
        var store = new Data.TreeStore({
            url : url,
            autoLoad : false,
            autoSync : true
        });

        var selectedType = null;
        var tab = new Tab.TabPanel({
            render : '#tab',
            elCls : 'nav-tabs',
            autoRender: true,
            children:MENU_TYPES.slice(0)
        });
        tab.on('selectedchange',function(ev) {
            selectedType = ev.item.get("type");
            store.set('lastParams', {});
            store.load({type: selectedType});
        });
        tab.setSelected(tab.getItemAt(0));

        //平台菜单
        var tree = new TreeGrid({
            render : '#menuGrid',
            store : store,
            showRoot : false,
            width : '100%',
            columns : [
                {title: 'ID', dataIndex: 'id', width: '15%'},
                {dataIndex: 'parent_id', visible : false},
                {title: '名称', dataIndex: 'name', width: '10%'},
                {title: 'url', dataIndex: 'url', width: '45%'},
                {title: '请求方式', dataIndex: 'method', width: '10%'},
                {title: '类型', dataIndex: 'type', width: '10%', renderer: function(value, obj){
                    return MENU_TYPES[value].text;
                }},
                {title: '操作', dataIndex: '', width: '10%', renderer: function (value, obj) {
                    var addStr = '<shiro:hasPermission name="/clmp/menu:post"><span class="grid-command btn-add" title="新增">新增</span></shiro:hasPermission>';
                    var editStr = '<shiro:hasPermission name="/clmp/menu/*:post"><span class="grid-command btn-edit" title="编辑">编辑</span></shiro:hasPermission>';
                    var delStr = '<shiro:hasPermission name="/clmp/menu/*:delete"><span class="grid-command btn-del" title="删除">删除</span></shiro:hasPermission>';
                    return addStr + editStr + delStr;
                }}
            ]
        });
        //监听点击单元格时间，新增、删除和编辑记录
        tree.on('cellclick', function (ev) {
            var ele = $(ev.domTarget); //点击的Dom
            if (ele.hasClass('grid-command btn-del')) {
                deleteRecord(ev.record);
            } else if (ele.hasClass('grid-command btn-edit')) {
                editRecord(ev.record);
            } else if (ele.hasClass('grid-command btn-add')) {
                addRecord(ev.record);
            }
        });
        tree.render();

        //表单
        var form = new Form.HForm({
            srcNode: '#ModelForm',
            submitType: 'ajax',
            callback: function (data) {
                if (data.status == 1) {
                    BUI.Message.Alert('操作成功');
                    var param = {};
                    if (form.get("updateType") != "noType"){
                        if ((form.get("updateType") == "hasType")){
                            var selectedItem = tree.getSelected();
                            var parentItem = selectedItem.parent;
                            param.id = parentItem.id ? (parentItem.children.length <= 1 ? parentItem.parent.id : parentItem.id) : null;
                        } else {
                            var selectedItem = tree.getSelected();
                            param.id = selectedItem ? selectedItem.id : null;
                        }
                    }
                    store.load(param);
                    dialog.close();
                } else {
                    BUI.Message.Alert('操作失败:' + data.msg);
                }
            }
        })
        form.render();

        //对话框
        var dialog = new Overlay.Dialog({
            title: '菜单',
            width: 800,
            height: 560,
            mask: true,
            buttons: [],
            contentId: 'ModelFormDialog'
        });
        //对话框关闭事件
        dialog.on("closed", function(e){
            form.clearFields();
            form.set("updateType", null);
            $('#parent_item').find(':not(:first)').remove();
        });

        //工具栏
        <shiro:hasPermission name="/clmp/menu:post">
        var bar = new Toolbar.Bar({
            render : '#toolbar',
            autoRender : true,
            elCls: 'toolbar',
            children : [{
                xtype:'button',
                btnCls : 'button button-white',
                text:'<i class="icon-plus"></i>新增',
                listeners : {
                    click : function(event){
                        loadParentItems(null, selectedType);
                        dialog.show();
                        form.set('action', url);
                        form.set('method', 'post');
                        form.setFieldValue(module +'.type', selectedType);
                    }
                }
            }]
        });
        </shiro:hasPermission>

        function loadAllConstantItem(){
            var menuTypeItem = $("select[name='menu.type']");
            for (var i in MENU_TYPES) {
                menuTypeItem.append('<option value="'+ i +'" >'+ MENU_TYPES[i].text +'</option>')
            }
        }
        loadAllConstantItem();

        $("select[name='menu.type']").change(function(){
            form.set('updateType', "hasType");
            loadParentItems(null, this.value);
        });

        /*
         * 加载父选项
         * @param record 选中该记录（不传即不选中）
         */
        function loadParentItems(record, type){
            $.ajax({
                url : url + "/getParentItems",
                type : "get",
                data : {type : type},
                cache : false,
                async : false,
                dataType : "json",
                success : function(data){
                    var parentItem = $('#parent_item');
                    parentItem.find(':not(:first)').remove();
                    for (var i in data) {
                        if (record && record.id == data[i].id)
                            continue;
                        parentItem.append('<option value="'+ data[i].id +'">'+ data[i].name +'</option>')
                    }
                }
            });
        }

        //新增一条记录
        function addRecord(record){
            loadParentItems(null, selectedType);
            dialog.show();
            form.setFieldValue(module +'.parent_id', record.id);
            form.setFieldValue(module +'.type', selectedType);
            form.set('action', url);
            form.set('method', 'post');
        }

        //编辑一条记录
        function editRecord(record){
            loadParentItems(record, selectedType);
            form.set('action', url + "/" + record.id);
            form.set('method', "POST");
            form.set('updateType', "noType");
            for (var name in record) {
                form.setFieldValue(module+'.' + name, record[name]);
            }
            dialog.show();
        }

        //删除一条记录
        function deleteRecord(record){
            BUI.Message.Confirm('确认要删除选中的记录么？', function () {
                $.ajax({
                    url: url + "/" + record.id,
                    dataType: 'json',
                    type: 'DELETE',
                    cache : false,
                    success: function (data) {
                        if (data.status == 1) {
                            BUI.Message.Alert('操作成功');
                            var parentItem = record.parent;
                            var param = {};
                            if (parentItem && parentItem.children.length == 1){
                                if (parentItem.parent){
                                    param.id = parentItem.parent.id;
                                }
                            }
                            store.load(param);
                        } else {
                            BUI.Message.Alert('操作失败:' + data.msg);
                        }
                    }
                });
            }, 'question');
        }
    });
</script>
</body>
</html>